//
//  FlutterQQApiHandler.m
//  Pods-Runner
//
//  Created by lu on 8/11/2019.
//

#import "FlutterQQApiHandler.h"
#import "QQSdkCallManager.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import "AppUtils.h"
#import "ThumbnailHelper.h"
#import "NSStringWrapper.h"

@implementation FlutterQQApiHandler

NSObject <FlutterPluginRegistrar> *_qqRegistrar;

- (instancetype)initWithRegistrar:(NSObject <FlutterPluginRegistrar> *)registrar {
    self = [super init];
    if (self) {
        _qqRegistrar = registrar;
    }
    
    return self;
}

// MARK: - QQ登录

// qq注册
- (void)qqRegisterWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSString *qqAppId = call.arguments[@"appId"];
    NSString *universalLinks = call.arguments[@"iOSUniversalLinks"];
    
    Boolean isSuccess = [[QQSdkCallManager getInstance] initQQWithAppId:qqAppId universalLinks:universalLinks];
    if (isSuccess) {
        result(@YES);
    } else {
        result(@NO);
    }
}

// QQ授权
- (void)qqAuthWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSArray* permissions = [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_SIMPLE_USER_INFO, kOPEN_PERMISSION_GET_USER_INFO, nil];
    Boolean isSuccess = [[QQSdkCallManager getInstance].tententOAuth authorize:permissions];
    NSLog(@"QQ授权=：%d", isSuccess);
    if (isSuccess) {
        result(@YES);
    } else {
        result(@NO);
    }
}

// 是否安装QQ
- (void)qqIsInstalledWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    Boolean isQQInstalled = [TencentOAuth iphoneQQInstalled];
    NSLog(@"是否安装QQ=：%d", isQQInstalled);
    if (isQQInstalled) {
        result(@YES);
    } else {
        result(@NO);
    }
}

// 退出QQ
- (void)qqLogoutWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSLog(@"退出QQ=");
    [[QQSdkCallManager getInstance].tententOAuth logout:[QQSdkCallManager getInstance]];
}

// 获取QQ用户信息
- (void)qqGetUserInfoWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    Boolean isGetUserInfoSuccess = [[QQSdkCallManager getInstance].tententOAuth getUserInfo];
    NSLog(@"获取QQ用户信息=：%d", isGetUserInfoSuccess);
    if (isGetUserInfoSuccess) {
        result(@YES);
    } else {
        result(@NO);
    }
}

// MARK: - QQ分享

// 分享文本到QQ - 文本分享，iOS只支持分享到qq，不支持qq空间
- (void)qqShareTextWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSString *title = call.arguments[@"title"];
    NSString *targetScene = call.arguments[@"targetScene"];

    if ([targetScene isEqualToString:@"Friend"]) {
        // 分享给好友
        //开发者分享的文本内容
        QQApiTextObject *txtObj = [QQApiTextObject objectWithText:title];
        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:txtObj];
        //将内容分享到
        QQApiSendResultCode sent = [QQApiInterface sendReq:req];
        if (sent == 0) {
            result(@YES);
        } else {
            result(@NO);
        }
        NSLog(@"分享文本到QQ=：%ld", (long)sent);
    } else {
        // iOS不支持文本分享到qq空间
        NSLog(@"文本分享iOS不支持分享到qq空间");
        result(@NO);
    }
}

// 分享网络图片到QQ - 图片分享，iOS只支持分享到qq，不支持qq空间
- (void)qqShareImageWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
//    NSString *title = call.arguments[@"title"];
//    if (title == nil) {
//        title = @"QQ分享";
//    }
    NSString *networkImageUrl = call.arguments[@"networkImageUrl"];
    FlutterStandardTypedData *imageData = call.arguments[@"imageData"];
    
    if (imageData == nil) {
        if (networkImageUrl == nil || [networkImageUrl isEqualToString:@""]) {
            result(@NO);
            return;
        }
    }
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        NSData *tempImageData = nil;
        if (imageData == nil) {
            //下载图片
            NSURL *imageURL = [NSURL URLWithString:networkImageUrl];
                tempImageData = [NSData dataWithContentsOfURL:imageURL];
            //    UIImage *thumbnailImage = [self getThumbnail:networkImageUrl size:32765];
            //    NSData *thumbnailImageData = UIImagePNGRepresentation(thumbnailImage);
        } else {
            tempImageData = imageData.data;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //开发者分享图片数据
            QQApiImageObject *imgObj = [QQApiImageObject objectWithData:tempImageData
                                                       previewImageData:tempImageData
                                                                  title: @"QQ分享"
                                                       description :@""];
            SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:imgObj];
            
            if (req != nil) {
                //将内容分享到
                QQApiSendResultCode sent = [QQApiInterface sendReq:req];
                if (sent == 0) {
                    result(@YES);
                } else {
                    result(@NO);
                }
            } else {
                result(@NO);
            }
        });
    });
}

// 分享音乐到QQ
- (void)qqShareMusicWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
//    //分享跳转
//    URLNSString *url = @"http://xxx.xxx.xxx/";
//    //分享图预览图URL地址
//    NSString *previewImageUrl = @"preImageUrl.png";
//    //音乐播放的网络流媒体地址
//    NSString *flashURL = @"xxx.mp3 ";
//    QQApiAudioObject *audioObj =[QQApiAudioObject
//    objectWithURL :[NSURL URLWithString:url]
//    title:@"title"
//    description:@"description"
//    previewImageURL:[NSURL URLWithString:previewImageUrl]];
//    //设置播放流媒体地址
//    [audioObj setFlashUrl:flashURL];
//    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:audioObj]
//    //将内容分享到qq
//    //QQApiSendResultCode sent = [QQApiInterface sendReq:req];
//    //将被容分享到qzone
//    QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
}

// 分享网页到QQ
- (void)qqShareWebPageWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSString *title = call.arguments[@"title"];
    NSString *targetScene = call.arguments[@"targetScene"];
    NSString *targetUrl = call.arguments[@"targetUrl"];
    NSString *summary = call.arguments[@"summary"];
    NSString *networkImageUrl = call.arguments[@"networkImageUrl"];
    FlutterStandardTypedData* imageTypeData = (FlutterStandardTypedData*)call.arguments[@"imageData"];
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        // 链接
        NSString *utf8String = [targetUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        NSData *imageData;
        if (networkImageUrl != (id) [NSNull null]) {
           NSLog(@"缩略图 thumbnail: %@", networkImageUrl);
           UIImage *thumbnailImage = [self getThumbnail:networkImageUrl size:32765];
           imageData = UIImageJPEGRepresentation(thumbnailImage, 1.0f);
        } else if (imageTypeData != (id) [NSNull null]) {
           NSLog(@"微信分享网页 -- 02");
           // imageData
           imageData = imageTypeData.data;
           NSLog(@"微信分享网页 -- 03");
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            QQApiNewsObject *newsObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:utf8String] title:title description:summary previewImageData:imageData];
            
            SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
            QQApiSendResultCode sent;
            if ([targetScene isEqualToString:@"Friend"]) {
                // 分享给qq好友
                sent = [QQApiInterface sendReq:req];
            } else {
                // 分享给qq空间
                sent = [QQApiInterface SendReqToQZone:req];
            }
            if (sent == 0) {
                result(@YES);
            } else {
                result(@NO);
            }
        });
    });
}

// 获取网络图片缩略图
- (UIImage *)getThumbnail:(NSString *)thumbnail size:(NSUInteger)size {
    UIImage *thumbnailImage = nil;

        if ([AppUtils isBlank:thumbnail]) {
            return nil;
        }
    
        NSLog(@"0-");

        if ([thumbnail hasPrefix:@"assets://"]) {
            NSData *imageData2 = [NSData dataWithContentsOfFile:[self readImageFromAssets:thumbnail]];
            UIImage *tmp = [UIImage imageWithData:imageData2];
            thumbnailImage = [ThumbnailHelper compressImage:tmp toByte:size isPNG:FALSE];
            NSLog(@"1-");
        } else {
            NSURL *thumbnailURL = [NSURL URLWithString:thumbnail];
            NSData *thumbnailData = [NSData dataWithContentsOfURL:thumbnailURL];
            UIImage *tmp = [UIImage imageWithData:thumbnailData];
            thumbnailImage = [UIImage imageWithData:[self imageWithImage:tmp scaledToSize:CGSizeMake(100, 100)]];
            //缩略图要小于32KB，否则无法调起微信,32KB = 32*1024B=32678
//            thumbnailImage = [ThumbnailHelper zipImageWithUrl:thumbnail];
//            thumbnailImage = [ThumbnailHelper compressImage:tmp toByte:size isPNG:FALSE];
            NSLog(@"3-");
        }
        
        NSLog(@"4-");

        return thumbnailImage;
}


// ------这种方法对图片既进行压缩，又进行裁剪
- (NSData *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImageJPEGRepresentation(newImage, 0.8);
}

// 从项目读取图片
- (NSString *)readImageFromAssets:(NSString *)imagePath {
    NSArray *array = [self formatAssets:imagePath];
    
    NSLog(@"array-: %@", array);
    
    NSString *key;
    if ([AppUtils isBlank:array[1]]) {
        key = [_qqRegistrar lookupKeyForAsset:array[0]];
    } else {
        key = [_qqRegistrar lookupKeyForAsset:array[0] fromPackage:array[1]];
    }
    
    NSLog(@"5-: %@", key);
    
    return [[NSBundle mainBundle] pathForResource:key ofType:nil];
}

- (NSArray *)formatAssets:(NSString *)originPath {
    NSString *path = nil;
    NSString *packageName = @"";
    NSInteger from = [@"assets://" length];
    NSInteger to = [originPath length];
    NSString *pathWithoutSchema = [originPath substringFromIndex:from toIndex:to];
    NSInteger indexOfPackage = [pathWithoutSchema lastIndexOfString:@"?package="];

    if (indexOfPackage != JavaNotFound) {
        path = [pathWithoutSchema substringFromIndex:0 toIndex:indexOfPackage];
        int begin = indexOfPackage + [@"?package=" length];
        packageName = [pathWithoutSchema substringFromIndex:begin toIndex:[pathWithoutSchema length]];
    } else {
        path = pathWithoutSchema;
    }

    return @[path, packageName];
}

@end
